package org.shj.thread.book2.chapter12.active;


class ActivationQueue {

	private static final int MAX_REQ = 100;
	
	private final MethodRequest[] reqQue;
	
	private int tail;
	private int head;
	private int count;
	
	public ActivationQueue(){
		this.reqQue = new MethodRequest[MAX_REQ];
		this.head = 0 ; 
		this.tail = 0;
		this.count = 0;
	}
	
	public synchronized void putRequest(MethodRequest req){
		while (count >= reqQue.length){
			try{
				wait();
			}catch(InterruptedException e){
				
			}
		}
		
		reqQue[tail] = req;
		
		tail = (tail+1) % reqQue.length;
		count++;
		notifyAll();
	}
	
	public synchronized MethodRequest takeRequest(){
		while (count <= 0){
			try{
				wait();
			}catch(InterruptedException e){
				
			}
		}
		MethodRequest req = reqQue[head];
		head = (head+1) % reqQue.length;
		count--;
		notifyAll();
		return req;
	}
}
